import 'package:url_launcher/url_launcher_string.dart';

import '../../util.dart';
import '../check_update.dart';
import 'index.dart';

class VersionUpdateViewController extends GetxController {
  VersionUpdateViewController();

  final state = VersionUpdateViewState();

  void actionUpdate() {
    state.isUpdating = true;

    if (GetPlatform.isAndroid) {
      update(['update']);
      CheckUpdate().download(
        state.md.androidUrl,
        onReceiveProgress: (received, total) {
          if (total <= 0) return;
          state.received = received.toDouble();
          state.total = total.toDouble();
          state.totalSize = FileManager().renderSize(state.total);
          update(['progress']);
        },
      ).then((value) {
        if (value) {
          // Get.back();
          state.isUpdating = false;
          update(['update']);
        } else {
          state.isUpdating = false;
          update(['update']);
        }
      });
    } else if (GetPlatform.isIOS) {
      launchUrlString(state.md.iosUrl);
    }
  }

  void back() {
    SpUtil().setStr(StorageKeys.app_update_no_tip, state.md.versionName);
    Get.back();
  }

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
    state.md = Get.arguments;
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }
}
